/*
 *  PrivateSnapshot.java        22-ott-2009
 *   
 * Copyright (c) 2009 mentalsmash.org
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 *  The use of the Apache License does not indicate that this project is
 *  affiliated with the Apache Software Foundation.
 */

package org.mentalsmash.tazio.transactions.objects;

import java.io.Serializable;
import java.util.Map;

import org.mentalsmash.documentation.Concurrency;
import org.mentalsmash.tazio.commons.identifiers.OID;
import org.mentalsmash.tazio.transactions.Transaction;
import org.mentalsmash.tazio.transactions.util.Utility;

import com.google.common.collect.Maps;

/**
 * A <tt>PrivateSnapshot</tt> instance represents a copy of any
 * {@link TransactionalObject} state local to a {@link Transaction} instance.
 * <p>
 * The state of a {@link TransactionalObject} is assumed to be the value of the
 * properties of the object expressed following the <i>JavaBeans</i> notation.
 * Therefore a <tt>PrivateSnapshot</tt> enlists the value of each property that
 * has a pair of accessible get/set accessors in the referenced
 * {@link TransactionalObject}
 * </p>
 * <p>
 * When a private snasphost of a {@link TransactionalObject} is created the
 * value of properties of primitives types are copied into the snapshot. For
 * properties that reference other {@link TransactionalObject} special handling
 * is needed:
 * <ol>
 * <li>
 * The chain of references of properties that start from this reference type
 * property is walked, and for each {@link TransactionalObject} reference a
 * private snapshot of that object is made.</li>
 * <strong>ACTUALLY THERE SHOULD NOT BE NEED FOR THAT</strong>: just the oid of
 * that object is registered, and that object gets snapshoot only if the
 * property is accessed
 * <li>
 * It is registered in the map the OID of the {@link TransactionalObject}</li>
 * <ol>
 * </p>
 * 
 * @author Andrea Reale
 * @version 0.0.1
 */
@Concurrency(concurrentAccess = false, specification = "a <tt>PrivateSnapshot</tt> instance should be accept only by one "
	+ "thread, and that is the thread that owns the Transactions that ons the "
	+ "Private Snapshot. No synchronization is needed.")
class PrivateSnapshot implements Snapshot {

    private static final long serialVersionUID = -3033861302124564388L;

    /**
     * The unique identifier of the object that this <tt>PrivateSnapshot</tt> is
     * taken from
     */
    private final OID objectID;

    /**
     * The version field reflects the seqNo of the last Transaction that wrote
     * the Object before it had got snapshotted.
     */
    private final long version;

    /**
     * The Map of properties having proper annotiations for Transactional Object
     * this snapshot refers to.
     * <p>
     * The key of the map is the name of the property the entry refers to, and
     * the value is a reference to the value of that property (for reference
     * types) or a copy of the value of that property (for primitive types).
     * </p>
     * <p>
     * Since a {@link TranasactionalObject} may contain references only to other
     * <tt>TransactionalObject</tt>s or primitivs, it turns out that the values
     * of this map are OIDs or copies of primitive data.
     * </p>
     */
    private final Map<String, PropertySnapshot> privateProperties;

    /**
     * Creates a new <tt>PrivateSnapshot</tt> instance for a Transactional
     * Object having the given <code>oid</code> and the given
     * <code>version</code>
     * 
     * @param oid
     *            the object identifier of the transactional object being
     *            snapshotted
     * @param version
     *            the version of the transactional object. i.e. the
     *            <code>sequence
     *                number</code> of the last transaction that wrote that
     *            object.
     */
    public PrivateSnapshot(final OID oid, final long version) {
	this.objectID = oid;
	this.version = version;
	this.privateProperties = Maps.newHashMap();
	;
    }

    /**
     * Reads the value of a property from the snapshot.
     * 
     * @param name
     *            the name of the property to read
     * @return the value of the property
     * @throws NoSuchPropertyException
     *             if no property named <code>name</code> is in the snapshot
     * @see NullPropertyValue
     */
    public Serializable readProperty(final String name)
	    throws NoSuchPropertyException {
	final PropertySnapshot prop = this.privateProperties.get(name);
	if (prop == null) {
	    throw new NoSuchPropertyException(
		    "The snapshot does not have any property named " + name);
	}

	return prop.getPropertyValue();
    }

    /**
     * Updates the value of a property in the map of private properties.
     * 
     * @param name
     *            the name of the property to update
     * @param value
     *            the value for the property to be set
     * @throws NoSuchPropertyException
     *             if no property named <code>name</code> is in the snapshot
     */
    public void updateProperty(final String name, final Serializable value)
	    throws NoSuchPropertyException {
	final PropertySnapshot prop = this.privateProperties.get(name);
	if (prop == null) {
	    throw new NoSuchPropertyException(
		    "The snapshot does not have any property named " + name);
	}

	prop.setPropertyValue(value);
    }

    /**
     * Adds a property to the map of private properties.
     * <p>
     * If a property with the given <code>name</code> does already exists its
     * value its updated and no property is added
     * </p>
     * 
     * @param name
     *            the name of the property to add
     * @param value
     *            the value of the property
     */
    public void addProperty(final String name, final Serializable value) {
	PropertySnapshot prop = this.privateProperties.get(name);
	if (prop != null) {
	    prop.setPropertyValue(value);
	} else {
	    prop = new PropertySnapshot(value);
	    this.privateProperties.put(name, prop);
	}
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mentalsmash.tazio.transactions.model.Snapshot#getOID()
     */
    public OID getOID() {
	return this.objectID;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.mentalsmash.tazio.transactions.model.Snapshot#getInitialVersion()
     */
    public long getInitialVersion() {
	return this.version;
    }

    @Override
    public boolean isSetSnapshot() {
	return false;
    }

}

/**
 * Represent a property in a Tazio Transactional objects.
 * <p>
 * A property is identified by a pair of annotations
 * {@link org.mentalsmash.tazio.transactions.PropertyGetter} and
 * {@link org.mentalsmash.tazio.transactions.PropertySetter}
 * </p>
 * 
 * @author Andrea Reale
 * @version 0.0.1
 */
class PropertySnapshot implements Serializable {

    private static final long serialVersionUID = -2501458453632728776L;

    // a property can only be a primitive type or a reference to an OID
    private final boolean isPrimitiveType;

    private Serializable propertyValue;

    public PropertySnapshot(final Serializable propertyValue) {

	if (propertyValue == null) {
	    throw new IllegalPropertyTypeException(
		    "Property cannot be null... remember, use the NULL OID instead");
	}

	if (!(Utility.isPrimitiveType(propertyValue) || propertyValue instanceof OID)) {
	    throw new IllegalPropertyTypeException(
		    "Properties of a TransactionalObject"
			    + "must be either primitives or other TransactionalObjects");
	}
	this.isPrimitiveType = propertyValue.getClass().isPrimitive();
	setPropertyValue(propertyValue);
    }

    /**
     * @param propertyValue
     *            the propertyValue to set
     */
    public synchronized void setPropertyValue(final Serializable propertyValue) {
	if (!(Utility.isPrimitiveType(propertyValue) || propertyValue instanceof OID)) {
	    throw new IllegalPropertyTypeException(
		    "Properties of a TransactionalObject"
			    + "must be either primitives or other TransactionalObjects");
	} else if (propertyValue.getClass().isPrimitive() != this.isPrimitive()) {
	    throw new IllegalPropertyTypeException(
		    "Property type and given value do not mathc");
	}

	this.propertyValue = propertyValue;
    }

    /**
     * @return the propertyValue
     */
    public synchronized Serializable getPropertyValue() {

	return this.propertyValue;
    }

    public synchronized boolean isPrimitive() {
	return this.isPrimitiveType;
    }

}
